<?php

/**
 * Created by PhpStorm.
 * User: Yieong
 * Date: 2017/1/15
 * Time: 下午2:41
 */
class OnlineCommand extends CConsoleCommand {

    public function run($args) {

        $api = new ApiService();
        // 通过接口获得当前在线数
        $apiTmp= $api->getOnline();
        if(!isset($apiTmp['data']['Num'])){
            $apiTmp= $api->getOnline();
        }
        if(!isset($apiTmp['data']['Num'])){
            $apiTmp= $api->getOnline();
        }
        $currentOnline  = isset($apiTmp['data']['Num']) ? $apiTmp['data']['Num'] : 0;

        // 获得上次在线人数
        $path = Yii::getPathOfAlias('docroot').'/logs/online_num/';
        if(!is_dir($path)){
            mkdir($path, 0777, true);
        }

        $file = $path . 'online_num.check.' . date('Ymd');

        $config = $this->getConfig();
        $lastOnline = isset($config['online_num']) ? $config['online_num'] : 0;
        $threshold  = $config['threshold'];

        $date = date('Y-m-d H:i:s');

        if($lastOnline >= 0) {
            $dValue = abs($lastOnline - $currentOnline);

            if ($dValue > $threshold) {
                // 保存报警
                $model = new ModOnlineWarning();
                $model->current_online_num = $currentOnline;
                $model->last_online_nume = $lastOnline;
                $model->create_time = time();
                $model->save();

                // 发送报警邮件
                $mail = $config['mail_list'];
                self::sendEmail($mail, "[{$date}] 上一分钟的在线人数是 {$lastOnline}, 本分钟的在线人数是 {$currentOnline}, 差值为 {$dValue}, 超过了设定的阈值 {$threshold}, 请确认是否有问题。", '数据后台在线报警');
            }
        }

        // 保存上次的时间
        $this->setLastOnline($currentOnline);
        file_put_contents($file, "{$date}:last-{$lastOnline}:current-{$currentOnline}\r\n", FILE_APPEND);
        file_put_contents($file, json_encode($config['mail_list']).PHP_EOL, FILE_APPEND);

        echo 'success';
    }

    public static function sendEmail($address, $content, $title='数据后台', $attach=array(), $ccAddress=array()){

        if(empty($address) || empty($content)) return false;

        $mail = new PubMailer();                        // 建立邮件发送类

        $mail->IsHTML(true);                            // 设置HTML格式邮件
        $mail->IsSMTP();                                // 使用SMTP方式发送
        $mail->CharSet      = 'UTF-8';                  // 设置邮件的字符编码
        $mail->Host         = 'smtp.exmail.qq.com';     // 您的企业邮局域名
        $mail->SMTPSecure   = "ssl";	                // 以SSL方式连接。
        $mail->Port         = "465";                    // 端口号。
        $mail->SMTPAuth     = true;                     // 启用SMTP验证功能
        $mail->Username     = "lyht123456@ifeell.com";  // 邮局用户名(请填写完整的email地址)
        $mail->Password     = "Ats9900?";               // 邮局密码
        $mail->From         = "lyht123456@ifeell.com";  // 邮件发送者email地址
        $mail->Subject      = $title;                   // 邮件标题
        $mail->Body         = $content;                 // 邮件内容
        $mail->AltBody      = "text/html";
        $mail->Encoding     = "base64";
        $mail->FromName     = "数据后台";

        // 收件地址
        if(is_array($address)){
            foreach($address AS $v){
                if(!empty($v)){
                    $mail->AddAddress($v);
                }
            }
        }else{
            $mail->AddAddress($address);
        }

        // 抄送地址
        if(is_array($ccAddress)){
            foreach($ccAddress AS $v){
                if(!empty($v)){
                    $mail->AddCC($v);
                }
            }
        }else if(!empty($ccAddress)){
            $mail->AddCC($ccAddress);
        }

        // 附件地址
        if(!empty($attach)){
            foreach($attach as $v){
                $mail->AddAttachment($v['path'], $v['name']);
            }
        }

        return $mail->Send();
    }

    public function getConfig(){
        $model = new ModOnlineInfo();
        $result = $model->findByPk(1)->attributes;
        $result['mail_list'] = explode("\r\n", $result['mail_list']);
        return $result;
    }

    public function setLastOnline($online){
        $model = new ModOnlineInfo();
        $result = $model->updateByPk(1, array(
            'online_num'    => $online,
            'update_time'   => time()
        ));
        return $result['online_num'];
    }
}